package guo.xungenguser.controller;

import com.alibaba.fastjson.TypeReference;
import guo.xungengcommon.utils.R;
import guo.xungengcommon.vo.UserVo;
import guo.xungenguser.entity.User;
import guo.xungenguser.interceptor.UserInterceptor;
import guo.xungenguser.service.UserService;
import guo.xungenguser.utils.CommonUpload;
import guo.xungenguser.vo.UpdateInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
public class PersonalController {

    @Autowired
    UserService userService;

    /**
     * 个人中心页面
     * @param httpSession
     * @param model
     * @return
     */
    @GetMapping("/personal")
    public String myselfInfo(HttpSession httpSession, Model model){
        UserVo userVo = UserInterceptor.threadLocal.get();
        model.addAttribute("user",userVo);
        return "personindex";
    }

    /**
     * 更改个人中心信息
     * @param updateInfoVo
     * @return
     */
    @PostMapping("/person/update")
    public String updateInfo(UpdateInfoVo updateInfoVo,HttpSession session){
        System.out.println("updateinfo信息为: "+updateInfoVo);
        R r = userService.updateAllInfo(updateInfoVo);
        UserVo user = (UserVo) r.getData("user", new TypeReference<UserVo>() {
        });
        return "personindex";
    }

    /**
     * 更改个人中心图片请求
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/update/img")
    public String updateInfo(@RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("file信息为: "+file);
        CommonUpload commonUpload = new CommonUpload();
        R r = commonUpload.uploadimg(file);
        String ossUrl = (String) r.getData("ossUrl", new TypeReference<String>() {
        });
        System.out.println("上传到oss的路径为: "+ossUrl);

        //更新数据库 用户字段img
        userService.updateImg(ossUrl);

        return "personindex";
    }

}
